import request from '@/utils/request'

// 静态网站管理接口
const staticSiteURL = '/spider/api/static-site'

export function getStaticSiteList(args) {
  return request({
    url: `${staticSiteURL}/${args && ('?' + args) || ''}`,
    method: 'get'
  })
}

export function getStaticSite(id) {
  return request({
    url: `${staticSiteURL}/${id}`,
    method: 'get'
  })
}

export function createStaticSite(data) {
  return request({
    url: `${staticSiteURL}/`,
    headers: { 'content-type': 'application/json' },
    method: 'post',
    data: data
  })
}

export function updateStaticSite(id, data) {
  return request({
    url: `${staticSiteURL}/${id}`,
    headers: { 'content-type': 'application/json' },
    method: 'put',
    data: data
  })
}

export function deleteStaticSite(id) {
  return request({
    url: `${staticSiteURL}/${id}`,
    method: 'delete'
  })
}

// 静态网站分类管理接口
const categoryURL = '/spider/api/static-site-category'

export function getStaticSiteCategoryList(args) {
  return request({
    url: `${categoryURL}/${args && ('?' + args) || ''}`,
    method: 'get'
  })
}

export function getStaticSiteCategory(id) {
  return request({
    url: `${categoryURL}/${id}`,
    method: 'get'
  })
}

export function createStaticSiteCategory(data) {
  return request({
    url: `${categoryURL}/`,
    headers: { 'content-type': 'application/json' },
    method: 'post',
    data: data
  })
}

export function updateStaticSiteCategory(id, data) {
  return request({
    url: `${categoryURL}/${id}`,
    headers: { 'content-type': 'application/json' },
    method: 'put',
    data: data
  })
}

export function deleteStaticSiteCategory(id) {
  return request({
    url: `${categoryURL}/${id}`,
    method: 'delete'
  })
}

// 静态网页管理接口
const pageURL = '/spider/api/static-site-page'

export function getStaticSitePageList(args) {
  return request({
    url: `${pageURL}/${args && ('?' + args) || ''}`,
    method: 'get'
  })
}

export function getStaticSitePage(id) {
  return request({
    url: `${pageURL}/${id}`,
    method: 'get'
  })
}

export function createStaticSitePage(data) {
  return request({
    url: `${pageURL}/`,
    headers: { 'content-type': 'application/json' },
    method: 'post',
    data: data
  })
}

export function updateStaticSitePage(id, data) {
  return request({
    url: `${pageURL}/${id}`,
    headers: { 'content-type': 'application/json' },
    method: 'put',
    data: data
  })
}

export function deleteStaticSitePage(id) {
  return request({
    url: `${pageURL}/${id}`,
    method: 'delete'
  })
}

// 静态网页发布管理接口
export function publishStaticSitePage(id) {
  return request({
    url: `${pageURL}/publish/${id}`,
    method: 'post'
  })
}

export function unpublishStaticSitePage(id) {
  return request({
    url: `${pageURL}/unpublish/${id}`,
    method: 'post'
  })
}

// HTML模板管理接口
export function getHtmlTemplateList(params) {
  return request({
    url: '/spider/api/html-template/',
    method: 'get',
    params: params
  })
}

export function createHtmlTemplate(data) {
  return request({
    url: '/spider/api/html-template/',
    method: 'post',
    data
  })
}

export function updateHtmlTemplate(id, data) {
  return request({
    url: `/spider/api/html-template/${id}`,
    method: 'put',
    data
  })
}

export function deleteHtmlTemplate(id) {
  return request({
    url: `/spider/api/html-template/${id}`,
    method: 'delete'
  })
}

export function getHtmlTemplate(id) {
  return request({
    url: `/spider/api/html-template/${id}`,
    method: 'get'
  })
}

// 使用模板渲染页面预览
export function renderPageWithTemplate(pageId) {
  return request({
    url: `/spider/api/static-site-page/render/${pageId}`,
    method: 'get'
  })
}

// 菜单管理接口
const menuURL = '/spider/api/static-site-menu'

export function getStaticSiteMenuList(args) {
  return request({
    url: `${menuURL}/${args && ('?' + args) || ''}`,
    method: 'get'
  })
}

export function getStaticSiteMenu(id) {
  return request({
    url: `${menuURL}/${id}`,
    method: 'get'
  })
}

export function createStaticSiteMenu(data) {
  return request({
    url: `${menuURL}/`,
    headers: { 'content-type': 'application/json' },
    method: 'post',
    data: data
  })
}

export function updateStaticSiteMenu(id, data) {
  return request({
    url: `${menuURL}/${id}`,
    headers: { 'content-type': 'application/json' },
    method: 'put',
    data: data
  })
}

export function deleteStaticSiteMenu(id) {
  return request({
    url: `${menuURL}/${id}`,
    method: 'delete'
  })
}

// 菜单项管理接口
const menuItemURL = '/spider/api/static-site-menu-item'

export function getStaticSiteMenuItemList(args) {
  return request({
    url: `${menuItemURL}/${args && ('?' + args) || ''}`,
    method: 'get'
  })
}

export function getStaticSiteMenuItem(id) {
  return request({
    url: `${menuItemURL}/${id}`,
    method: 'get'
  })
}

export function createStaticSiteMenuItem(data) {
  return request({
    url: `${menuItemURL}/`,
    headers: { 'content-type': 'application/json' },
    method: 'post',
    data: data
  })
}

export function updateStaticSiteMenuItem(id, data) {
  return request({
    url: `${menuItemURL}/${id}`,
    headers: { 'content-type': 'application/json' },
    method: 'put',
    data: data
  })
}

export function deleteStaticSiteMenuItem(id) {
  return request({
    url: `${menuItemURL}/${id}`,
    method: 'delete'
  })
}

// 菜单树结构接口
export function getStaticSiteMenuTree(menuId) {
  return request({
    url: `/spider/api/static-site-menu-tree/${menuId}`,
    method: 'get'
  })
}

// 菜单选项接口
export function getStaticSiteMenuOptions(siteId) {
  return request({
    url: `/spider/api/static-site-menu-options/${siteId}`,
    method: 'get'
  })
}

// AI菜单重构相关接口
export function aiRebuildPageMenu(data) {
  return request({
    url: '/spider/api/ai-rebuild-page-menu',
    method: 'post',
    data
  })
}

export function aiRebuildCategoryMenu(data) {
  return request({
    url: '/spider/api/ai-rebuild-category-menu',
    method: 'post',
    data
  })
}

export function batchRebuildPagesMenu(data) {
  return request({
    url: '/spider/api/batch-rebuild-pages-menu',
    method: 'post',
    data
  })
}

// 流式响应处理函数
export function handleStreamResponse(response, onProgress, onResult, onError) {
  const reader = response.body.getReader()
  const decoder = new TextDecoder()

  function processStream() {
    return reader.read().then(({ done, value }) => {
      if (done) {
        return
      }

      const chunk = decoder.decode(value, { stream: true })
      const lines = chunk.split('\n')

      lines.forEach(line => {
        if (line.startsWith('data: ')) {
          try {
            const data = JSON.parse(line.substring(6))

            if (data.type === 'progress') {
              onProgress && onProgress(data.message)
            } else if (data.type === 'result') {
              onResult && onResult(data.data)
            } else if (data.type === 'error') {
              onError && onError(data.message)
            }
          } catch (e) {
            console.error('解析流数据失败:', e)
          }
        }
      })

      return processStream()
    })
  }

  return processStream()
}

// 流式AI菜单重构页面
export function aiRebuildPageMenuStream(data, onProgress, onResult, onError) {
  return fetch(`${process.env.VUE_APP_BASE_API}/spider/api/ai-rebuild-page-menu`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Token ${localStorage.getItem('token')}`
    },
    body: JSON.stringify(data)
  }).then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    return handleStreamResponse(response, onProgress, onResult, onError)
  })
}

// 流式AI菜单重构分类
export function aiRebuildCategoryMenuStream(data, onProgress, onResult, onError) {
  return fetch(`${process.env.VUE_APP_BASE_API}/spider/api/ai-rebuild-category-menu`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Token ${localStorage.getItem('token')}`
    },
    body: JSON.stringify(data)
  }).then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    return handleStreamResponse(response, onProgress, onResult, onError)
  })
}

// 流式批量重构页面菜单
export function batchRebuildPagesMenuStream(data, onProgress, onResult, onError) {
  return fetch(`${process.env.VUE_APP_BASE_API}/spider/api/batch-rebuild-pages-menu`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Token ${localStorage.getItem('token')}`
    },
    body: JSON.stringify(data)
  }).then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    return handleStreamResponse(response, onProgress, onResult, onError)
  })
}

// 一键创建目录页导航列表
export function createCategoryNavigation(menuId) {
  return request({
    url: `/spider/api/create-category-navigation/${menuId}`,
    method: 'post'
  })
}

// 批量保存菜单结构
export function batchSaveMenuStructure(menuId, menuItems) {
  return request({
    url: `/spider/api/batch-save-menu-structure/${menuId}`,
    method: 'post',
    headers: { 'content-type': 'application/json' },
    data: { menu_items: menuItems }
  })
}

// 生成菜单代码
export function generateMenuCode(menuId) {
  return request({
    url: `/spider/api/generate-menu-code/${menuId}`,
    method: 'post'
  })
}

// 快速导航替换（仅替换导航部分，节省AI成本）- 非stream版本
export function aiRebuildCategoryNavigationOnly(data) {
  return request({
    url: '/spider/api/ai-rebuild-category-navigation-only/',
    method: 'post',
    data: data
  })
}

// 快速导航替换（仅替换导航部分，节省AI成本）- stream版本
export function aiRebuildCategoryNavigationOnlyStream(data, onProgress, onResult, onError) {
  return fetch(`${process.env.VUE_APP_BASE_API}/spider/api/ai-rebuild-category-navigation-only`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Token ${localStorage.getItem('token')}`
    },
    body: JSON.stringify(data)
  }).then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    return handleStreamResponse(response, onProgress, onResult, onError)
  })
}

// AI修改HTML代码
export function aiModifyHtmlCode(data) {
  return request({
    url: '/spider/api/ai-modify-html-code/',
    method: 'post',
    data: data
  })
}
